package io.jt808.netty;

import io.jt808.multiService.PackageHolder;
import io.jt808.multiService.PackageItem;
import io.netty.channel.ChannelHandlerContext;
import io.norland.buffer.AutoBuffer;
import io.norland.proto.AbstractWrapper;
import io.jt808.proto.Wrapper;
import io.norland.server.ProtoFrameHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class Jt808ProtoFrameHandler extends ProtoFrameHandler {

    @Autowired
    private PackageHolder packageHolder;

    @Override
    public void handleRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("REGISTERED ID:" + ctx.channel().id().asLongText());
    }

    @Override
    public void handleUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.info("UNREGISTERED ID:" + ctx.channel().id().asLongText());
    }

    @Override
    public boolean handleMessageReceived(ChannelHandlerContext ctx, AbstractWrapper wrapper) {
        Wrapper req = (Wrapper) wrapper;
        if (req.isPacked()) {
            packageHolder.push(req);
            if (!packageHolder.isComplete(req.getTerminalSerialNo()
                    , req.requestProtocol())) {
                return false;
            }
            PackageItem packageItem =
                    packageHolder.getAndRemovePackageItem(req.getTerminalSerialNo()
                            , req.requestProtocol());
            AutoBuffer buffer = new AutoBuffer(packageItem.getCompleteBytes());
            req.readPackedData(buffer);
        }
        return true;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        log.info("READ COMPLETE ID:" + ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        log.error("Caught exception ID:"
                + ctx.channel().id().asLongText()
                + "exception message:" + cause.getMessage(), cause);
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        log.info("ACTIVE ID:" + ctx.channel().id().asLongText());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//        log.info("INACTIVE ID:" + ctx.channel().id().asLongText());
    }
}